<template>
  <Excel :total="orderStore.page.total" :handle="handle">
    <template #default="{ open }">
      <t-button theme="primary" @click="open()" variant="outline" style="margin-left: 20px" >
        <template #icon><t-icon name="download" /></template>
        {{ $t('common.excel') }}
      </t-button>
    </template>
  </Excel>
</template>
<script setup>
  import app from '@/app'
  import index from '../../index'
  import orderStore from '../../store'
  import Excel from '@/components/excel.vue'
  import { get } from '@/api/store/order'

  const plugin = index.plugin

  const handle = async (progress) => {
    let page = 1
    let data = []
    const where = orderStore.getWhere()
    const table = [
      ['OPERADOR', 'FECHA', 'NUMERACIÓN', 'TIPO', 'EXISTE FACTURA', 'DOC. RELACIONADO', 'BASE', 'TIPO IVA', 'CUOTO IVA', 'R.E.', 'IMPORTE', 'UNIDADES',  'DTO.', 'COSTE', 'GANANCIAS', 'NOTA', 'CLIENTE', 'CIF/NIF', 'DIR. CLIENTE', 'COD.POSTAL', 'CIUDAD']
    ]
    const total = []

    do {
      // 查询 分页重置
      data = (await get({ ...where, page, page_size: 500 })).data
      data.forEach(item => {
        // 税统计
        const tax = []
        // 开头字段
        const before = [
          item.account_name,
          app.time.load(item.status_time).date(),
          item.code,
          plugin.t('order.ticket_text.' + item.ticket),
          item.ticket_open,
          item.code_key,
        ]
        // 结尾字段
        const after = [
          item.remarks,
          item.client_name,
          item.client_data.tax ?? '',
          item.client_data.address ?? '',
          item.client_data.zip ?? '',
          item.client_data.city ?? '',
        ]
        // 首次第一行总的订单，如果税只有一个，那就这行不显示了
        if(item.tax.length > 1) {
          table.push([
            ...before, 
            parseFloat(item.money_tax),
            '',
            parseFloat(item.tax_money),
            parseFloat(item.req_money),
            parseFloat(item.money),
            parseFloat(item.count),
            parseFloat(item.discount_money),
            parseFloat(item.cost_money),
            parseFloat(item.profit_money),
            ...after
          ])
        }
        

        // 循环订单税
        item.tax.forEach(tax => {
          // 是否累加
          let index = total.findIndex(itemTotal => itemTotal[2] == parseFloat(tax.tax) && itemTotal[4] == parseFloat(tax.req))
          if(index == -1) {
            index = total.push([
              '',
              0,
              parseFloat(tax.tax),
              0,
              parseFloat(tax.req),
              0,
              0
            ]) - 1
          }
          // 累加数据
          total[index][1] = app.math.add(tax.money_tax, total[index][1])
          total[index][3] = app.math.add(tax.tax_money, total[index][3])
          total[index][5] = app.math.add(tax.req_money, total[index][5])
          total[index][6] = app.math.add(tax.total, total[index][6])
        })

        // 循环商品
        item.goods.forEach(goods => {
          // 是否累加
          let index = tax.findIndex(itemTax => itemTax.tax == parseFloat(goods.tax) && itemTax.req == parseFloat(goods.req))
          if(index == -1) {
            index = tax.push({
              tax: parseFloat(goods.tax),
              req: parseFloat(goods.req),
              money_tax: 0,
              tax_money: 0,
              req_money: 0,
              count: 0,
              discount_money: 0,
              profit_money: 0,
              cost_money: 0,
              money: 0
            }) - 1
          }
          // 累加数据
          tax[index].discount_money = app.math.add(goods.discount_money, tax[index].discount_money)
          tax[index].count = app.math.add(goods.count, tax[index].count)
          tax[index].profit_money = app.math.add(goods.profit_money, tax[index].profit_money)
          tax[index].cost_money = app.math.add(goods.cost_money, tax[index].cost_money)
          tax[index].money_tax = app.math.add(goods.money_tax, tax[index].money_tax)
          tax[index].tax_money = app.math.add(goods.tax_money, tax[index].tax_money)
          tax[index].req_money = app.math.add(goods.req_money, tax[index].req_money)
          tax[index].money = app.math.add(goods.money, tax[index].money)
        })

        tax.forEach(itemTax => {
          table.push([
            ...before, 
            itemTax.money_tax,
            itemTax.tax + '%',
            itemTax.tax_money,
            itemTax.req_money,
            itemTax.money,
            itemTax.count,
            itemTax.discount_money,
            itemTax.cost_money,
            itemTax.profit_money,
            ...after
          ])
        })
      })
      page++
      progress(data.length)
    } while (data.length > 0)

    // 循环汇总
    const subtotal = ['Subtotal', 0, '', 0, '', 0, 0]
    total.forEach(item => {
      subtotal[1] = app.math.add(item[1], subtotal[1])
      subtotal[3] = app.math.add(item[3], subtotal[3])
      subtotal[5] = app.math.add(item[5], subtotal[5])
      subtotal[6] = app.math.add(item[6], subtotal[6])
    })

    return [
      ...table,
      [],
      ['', 'Base Imponible', 'IVA%', 'Importe IVA', 'REQ%', 'Importe REQ', 'Total'],
      ...total,
      subtotal
    ]
  }
</script>